/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;

/**
 *
 * @author TrongKhoa
 */
public class MyAutoCompleteTextArea extends JTextArea implements DocumentListener
{

    private static final String COMMIT_ACTION = "commit";

    void ClearVocabulary()
    {
        _words.clear();
    }

    private static enum Mode
    {

        INSERT, COMPLETION
    };
    private final List<String> _words;
    private Mode _mode = Mode.INSERT;

    public MyAutoCompleteTextArea()
    {
        this.setRows(10);
        this.setColumns(10);
        this.setLineWrap(true);
        this.setWrapStyleWord(true);

        getDocument().addDocumentListener(this);

        InputMap im = getInputMap();
        ActionMap am = getActionMap();
        im.put(KeyStroke.getKeyStroke("TAB"), COMMIT_ACTION);
        am.put(COMMIT_ACTION, new CommitAction());

        _words = new ArrayList<String>(6);
    }

    public void AddVocabulary(String vocal)
    {
        _words.add(vocal);
        Collections.sort(_words);
    }

    public void AddRangeVocabulary(String[] vocals)
    {
        _words.addAll(Arrays.asList(vocals));
        Collections.sort(_words);
    }

    private class CompletionTask implements Runnable
    {

        String completion;
        int position;

        CompletionTask(String completion, int position)
        {
            this.completion = completion;
            this.position = position;
        }

        public void run()
        {
            insert(completion, position);
            setCaretPosition(position + completion.length());
            moveCaretPosition(position);
            _mode = Mode.COMPLETION;
        }
    }

    private class CommitAction extends AbstractAction
    {

        public void actionPerformed(ActionEvent ev)
        {
            if (_mode == Mode.COMPLETION)
            {
                int pos = getSelectionEnd();
                insert(" ", pos);
                setCaretPosition(pos + 1);
                _mode = Mode.INSERT;
            }
            else
            {
                replaceSelection("\t");
            }
        }
    }

    @Override
    public void insertUpdate(DocumentEvent ev)
    {
        if (ev.getLength() != 1)
        {
            return;
        }

        int pos = ev.getOffset();
        String content = null;
        try
        {
            content = getText(0, pos + 1);
        }
        catch (BadLocationException e)
        {
            e.printStackTrace();
        }

        // Find where the word starts
        int w;
        for (w = pos; w >= 0; w--)
        {
            if (!Character.isLetter(content.charAt(w)))
            {
                break;
            }
        }
        if (pos - w < 1)
        {
            // Too few chars
            return;
        }


        String prefix = content.substring(w + 1).toLowerCase();
        int n = Collections.binarySearch(_words, prefix);
        if (n < 0 && -n <= _words.size())
        {
            String match = _words.get(-n - 1);
            if (match.startsWith(prefix))
            {
                // A completion is found
                String completion = match.substring(pos - w);
                // We cannot modify Document from within notification,
                // so we submit a task that does the change later
                SwingUtilities.invokeLater(
                        new CompletionTask(completion, pos + 1));
            }
        }
        else
        {
            // Nothing found
            _mode = Mode.INSERT;
        }
    }

    @Override
    public void removeUpdate(DocumentEvent e)
    {
    }

    @Override
    public void changedUpdate(DocumentEvent e)
    {
    }

    /*TEST
    public static void main(String[] args)
    {
        JFrame frm = new JFrame();
        frm.setVisible(true);
        frm.setSize(new Dimension(400, 400));
        MyAutoCompleteTextArea x = new MyAutoCompleteTextArea();
        x.AddRangeVocabulary(new String[]{"select", "from", "where", "group by", "order by"});
        JScrollPane scroll = new JScrollPane(x);
        frm.add(scroll);
    }
    * 
    */
}
